﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.Collections.Specialized;

namespace EETOP.OAuthSDK
{
    public class AbleAPI
    {

        private OAuthSettings Setting;
        OpenAuthRelyingParty openoauth;
        private string basic = ConfigurationManager.AppSettings["api_address"];
        public AbleAPI(OAuthSettings setting)
        {
            this.Setting = setting;
            openoauth = new OpenAuthRelyingParty(setting);
            if (openoauth.Response == null)
            {
                //连接able，获取request token,验证用户授权
                var httpRequest = openoauth.CreateRequest();
                string url = httpRequest.GetAuthorizationUrl();
                HttpContext.Current.Response.Redirect(url);
            }
           
        }
        private string DoRequest(string url, Method method,NameValueCollection paras)
        {
            BaseHttpRequest request = HttpRequestFactory.CreateHttpRequest(method, Setting);
            request.Token = openoauth.Response.Oauth_Access_Token;
            request.TokenSecret = openoauth.Response.Oauth_Access_Token_Secret;

            return request.Request(Util.AddParams(url, paras), string.Empty);
        }

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public  string GetUserInfo()
        {
            string url = basic + ConfigurationManager.AppSettings["GetUserInfo"];
            return DoRequest(url, Method.GET,null);
        }

        /// <summary>
        /// 获取当前用户所在企业列表
        /// </summary>
        /// <returns></returns>
        public string GetMyComs()
        {
            string url = basic + ConfigurationManager.AppSettings["ListMyComs"];
            return DoRequest(url, Method.GET, null);
        }

        /// <summary>
        /// 判断当前用户是否被授权使用当前应用
        /// </summary>
        /// <returns></returns>
        public string IsAuthorized()
        {
            string url = basic + ConfigurationManager.AppSettings["IsAuthorized"];
            return DoRequest(url, Method.GET,null);
        }

        
        /// <summary>
        /// 获取同事列表
        /// </summary>
        /// <param name="userID">公司ID</param>
        /// <returns></returns>
        public string MyColleagues(string companyID)
        {
            string url = basic + ConfigurationManager.AppSettings["MyColleagues"];
            return DoRequest(url, Method.GET, new NameValueCollection { { "companyid", companyID } });
        }
        
        
    }
}
